package com.fare.taluo.core.domain.thread;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.util.PDFTextStripper;

import com.fare.taluo.conf.PropertyUtils;
import com.fare.taluo.core.domain.config.city.PortEntity;
import com.fare.taluo.core.domain.config.line.FlightInfoEntity;
import com.fare.taluo.core.domain.crawl.CrawlPropertiesLoader;
import com.fare.taluo.core.domain.crawl.adapter.sub.CAAirLinePdfAdaptor;
import com.fare.taluo.util.DateUtils;

public class CALinePdfParseThread extends Thread {
	private Map<String, PortEntity> voMap;

	@Override
	public void run() {

		PortEntity portApplication = new PortEntity();
		voMap = portApplication.findPortEntityToMap();
       
		InputStream input = null;
		CAAirLinePdfAdaptor adap = new CAAirLinePdfAdaptor(null);
		String url = "ftp://Airchina:AirChina03170ag@webftp.airchina.com.cn/cn.pdf";
		File pdfFile = null;
		PDDocument document = null;
		int fetchCount = PropertyUtils.getIntProperty("crawl.line.fail.repeat.times", CrawlPropertiesLoader.CONFIG_FILE);
		try{
			while(fetchCount > 0){
				try {
					System.out.println("parsing is running...");
					pdfFile = (File) adap.fetch(url); 
				} catch (Exception e) {
					e.printStackTrace();
					 fetchCount--;
					continue ;
					
				}
			  if(null != pdfFile){
					System.out.println("the length of file is "+pdfFile.length());
					 if(pdfFile.length()>40000){
						 break;
					 }
			  }
		      fetchCount--;
				
		    }
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		try {

			input = new FileInputStream(pdfFile);

			// 加载 pdf 文档

			document = PDDocument.load(input);

			/** 文档属性信息 **/

			PDDocumentInformation info = document.getDocumentInformation();

			// 获取内容信息

			PDFTextStripper pts = new PDFTextStripper();
			pts.setSortByPosition(false);
			pts.setStartPage(10);
			pts.setEndPage(435);
			String content = pts.getText(document);
			// FileWriter fileWriter=new FileWriter("d:\\Result.txt");
			List<List> listlist = new ArrayList<List>();
			String[] records = content
					.split("VALIDITY Days of Dep. Dep. Arr. Arr. Flight");//
			List<String> list = null;
			for (int i = 0; i < records.length; i++) {// 1
				String oneRecord = records[i];
				String[] str = oneRecord.split("From ");
				for (int j = 2; j < str.length; j++) {// 2
					String[] flightRecords = str[j].split("To ");
					for (int k = 0; k < flightRecords.length; k++) {// 3
						String rec = flightRecords[k];
						String fromCity = null;
						String toCity = null;

						String[] newStirng = rec.split("\r\n");
						for (int l = 0; l < newStirng.length; l++) {
							if (newStirng[l].contains(":")) { // 单条记录
								list = new ArrayList<String>();
								String[] temp = newStirng[l].replaceAll(" ",
										"@").split("@");
								list.add(temp[0]);// 保存开始日期
								list.add(temp[1]);// 保存结束日期
								StringBuffer sb = new StringBuffer();
								for (int m = 2; m < temp.length; m++) {
									sb.append(temp[m]);
								}
								list.add(this.getFrequence(sb.toString()));// 保存班次

								String subString = this
										.getContainsString(newStirng[l]);
								String[] subArray = subString.split(" ");
								for (int m = 0; m < subArray.length; m++) {
									if (!subArray[m].equals("")
											&& subArray[m] != "") {// 去掉空格
										if (checkNumber(subArray, m)) {// 将航站楼编号去掉

											list.add(subArray[m].trim());
										}

									}
								}

								listlist.add(list);
							}
						}
					}

				}
			}

			saveFlightInfo(listlist);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != input)
				try {
					input.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			if (null != document)
				try {
					document.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

		}
	}

	// 检查是不是航站楼
	public boolean checkNumber(String[] arr, int m) {
		if (isNumeric(arr[m])) {// 如果是单个数字则认为是航站楼号码
			return false;
		} else if (m > 1 && isCityCode(arr[m - 1]) && arr[m].length() < 2) {
			return false;
		} else {
			return true;
		}

	}

	public boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]?");
		return pattern.matcher(str).matches();
	}

	private boolean isCityCode(String str) {
		String regex = "[A-ZA-ZA-Z]";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(str);
		while (m.find()) {
			return true;
		}
		return false;
	}

	private String getCityInfo(String str) {
		String cityCode = null;
		String fromCityString = str;
		String regex = "\\(\\w*\\)";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(fromCityString);
		while (m.find()) {
			cityCode = m.group().replace("(", "").replace(")", "");
		}
		return cityCode;
	}

	private String getContainsString(String str) {
		String regex = "[A-Z].+$";// 这就是正则表达式了
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(str);
		while (m.find()) {
			return m.group();
		}
		return null;

	}

	/**
	 * get frequence
	 * 
	 * @param infoStr
	 * @return
	 */
	private String getFrequence(String infoStr) {
		String regex = "[A-Z]{3}";
		String[] arr = infoStr.split(regex);
		return arr[0].replaceAll("\\.", "");
	}

	private void saveFlightInfo(List<List> listlist) {
		for (Iterator iterator = listlist.iterator(); iterator.hasNext();) {
			List<String> listTemp = (List<String>) iterator.next();
			FlightInfoEntity entity = new FlightInfoEntity();
			PortEntity fromVO = voMap.get(listTemp.get(3));
			PortEntity transferVO = voMap.get(listTemp.get(6));// 没有第二段航程的话，中转航班就是目的地航班
			PortEntity toVO = null;
			if (listTemp.size() > 14) {//
				toVO = voMap.get(listTemp.get(13));//
			}

			if (fromVO != null) {
				entity.setEffectStartTime(listTemp.get(0));
				entity.setEffectEndTime(listTemp.get(1));
				entity.setFrequence(listTemp.get(2));
				entity.setFromCityName(fromVO.getCityName());
				entity.setFromCity(listTemp.get(3));
				if (listTemp.size() > 14 && transferVO != null && toVO != null) {// 不是直飞航班
					entity.setFlightStartTime(this.getTime(listTemp.get(4)));// 若有中转机场
					// 则flight_start_time->transfer_end_time
					// 为
					// 航程一时间，transfer_start_time->flight_end_time为航程二时间
					entity.setTransferEndTime(this.getTime(listTemp.get(5)));
					entity.setTransferCity(listTemp.get(6));
					entity.setTransferCityName(transferVO.getCityName());
					if (listTemp.get(7).contains("*")) {
						entity.setFirstShareFlight("y");
					} else {
						entity.setFirstShareFlight("n");
					}
					entity.setFlightNo(listTemp.get(7));// 航段一航班号
					entity.setFirstFlightType(listTemp.get(8));
					entity.setFirstClass(listTemp.get(9));
					entity.setTransferStartTime(this.getTime(listTemp.get(11)));
					entity.setFlightEndTime(this.getTime(listTemp.get(12)));
					entity.setToCity(listTemp.get(13));
					entity.setToCityName(toVO.getCityName());
					if (listTemp.get(14).contains("*")) {
						entity.setSecondShareFlight("y");
					} else {
						entity.setSecondShareFlight("n");
					}
					entity.setTransgerFlightNo(listTemp.get(14));// 航段二航班号
					entity.setSecondFlightType(listTemp.get(15));
					entity.setSecondClass(listTemp.get(16));
					entity.setEntryTime(new Date());
					entity.setCompanyCode("CA");
					entity.setCompanyName("中国国际航空");
                    entity.setFlightDate(DateUtils.dateToStr(new Date(), "MM-dd"));
					try {
						entity.save(entity);
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else if (transferVO != null) {// 直飞航班
					entity.setFlightStartTime(this.getTime(listTemp.get(4)));
					entity.setFlightEndTime(this.getTime(listTemp.get(5)));
					entity.setToCity(transferVO.getCode());
					entity.setToCityName(transferVO.getCityName());
					if (listTemp.get(7).contains("*")) {
						entity.setFirstShareFlight("y");
					} else {
						entity.setFirstShareFlight("n");
					}
					entity.setFlightNo(listTemp.get(7));
					entity.setFirstFlightType(listTemp.get(8));
					if (listTemp.get(9).equals("NONSTOP")) {
						System.out.println("ffffffff");
					}
					entity.setFirstClass(listTemp.get(9));
					if (listTemp.get(10).equals("STOP")) {
						entity.setStopCity(this.getCityInfo(listTemp.get(11)));
					}
					entity.setEntryTime(new Date());
					entity.setCompanyCode("CA");
					entity.setCompanyName("中国国际航空");
					entity.setFlightDate(DateUtils.dateToStr(new Date(), "MM-dd"));
					try {
						entity.save(entity);
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					System.out.println("-----not suitable----");
				}

			}
		}

		// this.printAll(listlist);

		//JsonUtil.sendMessage("解析成功!");
	}

	private String getTime(String time) {
		if (time.contains("J")) {
			String newTime = time.substring(0, 2) + ":" + time.substring(2);
			return newTime.replace("J", "+1");
		} else {
			return time.substring(0, 2) + ":" + time.substring(2);
		}

	}

}
